use std::sync::Arc;

use chrono::Local;
use prisma_client_rust::QueryError;
use serde::{Serialize, Deserialize};

use crate::prisma::{PrismaClient, rsync};
use rspc::{Type};

#[derive(Clone, Serialize, Deserialize, Type, Debug)]
pub struct SaveRsyncData {
    pub id: String,
    pub name: String
}

pub struct RsyncManager {
}

impl RsyncManager {
    pub async fn all(client: Arc<PrismaClient>) -> Result<Vec<crate::prisma::rsync::Data>, QueryError> {
        Ok(
            client
                .rsync()
                .find_many(vec![])
                .exec()
                .await?
        )
    }

    pub async fn save(client: Arc<PrismaClient>, args: SaveRsyncData) -> Result<(), QueryError> {
        println!("{:?}", args);
        let imported_at = Local::now();
        let _ = client
            .rsync()
            .upsert(
                rsync::id::equals(args.id.clone().to_string()),
                (
                    args.id.clone().to_string(),
                    args.name.clone().to_string(),
                    vec![
                        rsync::created_at::set(imported_at.into()),
                        rsync::imported_at::set(Some(imported_at.into())),
                    ]
                ),
                vec![
                    rsync::name::set(args.name.clone().to_string()),
                    rsync::created_at::set(imported_at.into()),
                    rsync::imported_at::set(Some(imported_at.into())),
                ]
            ).exec().await?;

        Ok(())
    }
}
